<?php

namespace app\admin\controller\admin;

use app\admin\model\Admin;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Db;


/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class DataOverview extends Backend
{
    protected $noNeedRight = ['getData', 'get_table_data'];
    protected $model = null;
    protected $put_model = null;
    protected $uid = null;
    protected $group_id= 0;

//    protected $noNeedLogin = ['update_user'];
    protected $isSuperAdmin = false;
    public function _initialize()
    {
        parent::_initialize();
        $this->group_id = $this->auth->getGroupIds()[0];
    }
    /**
     * 查看
     */
    public function index()
    {
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }
        $column = [];
        $starttime = Date::unixtime('day', -6);
        $endtime = Date::unixtime('day', 0, 'end');
        $joinlist = Db("card_put_info")->where('create_time', 'between time', [$starttime, $endtime])
            ->field('create_time, audit_status, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(create_time), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
//        $joinlist = Db("user")->where('jointime', 'between time', [$starttime, $endtime])
//            ->field('jointime, status, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(jointime), "%Y-%m-%d") AS join_date')
//            ->group('join_date')
//            ->select();
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $userlist = array_fill_keys($column, 0);
        foreach ($joinlist as $k => $v) {
            $userlist[$v['join_date']] = $v['nums'];
        }

        $where = [];
        $install_total = Db::name('card_put_info')->where($where)->count();
        $data_where = $where;
        $data_where['create_time'] = ['between', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))]];
        // $today_install_total = Db::name('install')->where($data_where)->count();
        $today_install_total = Db::name('card_put_info')->where($data_where)->field('sum(put_price) as put_price,count(*) as num')->find();
        $data_where['create_time'] = ['between', [strtotime(date('Y-m-d 00:00:00', strtotime("-3 day"))), strtotime(date('Y-m-d 23:59:59'))]];
        // $three_install_total = Db::name('install')->where($data_where)->count();
        $three_install_total = Db::name('card_put_info')->where($data_where)->field('sum(put_price) as put_price,count(*) as num')->find();
        $data_where['create_time'] = ['between', [strtotime(date('Y-m-d 00:00:00', strtotime("-7 day"))), strtotime(date('Y-m-d 23:59:59'))]];
        //   $week_install_total = Db::name('install')->where($data_where)->count();
        $week_install_total = Db::name('card_put_info')->where($data_where)->field('sum(put_price) as put_price,count(*) as num')->find();
        $where['audit_status'] = 1;
        $install_total_set = Db::name('card_put_info')->where($where)->field('sum(put_price)/100 as put_price,count(*) as num')->find();
        if ($install_total_set['put_price'] == null) {
            $install_total_set['put_price'] = 0;
        } else {
            $install_total_set['put_price'] = sprintf("%.2f", substr(sprintf("%.3f", $install_total_set['put_price']), 0, -2));
        }
        $where['audit_status'] = 0;
        $install_total_no_set = Db::name('card_put_info')->where($where)->field('sum(put_price)/100 as put_price,count(*) as num')->find();
        if ($install_total_no_set['put_price'] == null) {
            $install_total_no_set['put_price'] = 0;
        } else {
            $install_total_no_set['put_price'] = sprintf("%.2f", substr(sprintf("%.3f", $install_total_no_set['put_price']), 0, -2));
        }
        $this->view->assign([
            'install_total' => $install_total,
            'today_install_total' => $today_install_total,
            'three_install_total' => $three_install_total,
            'week_install_total' => $week_install_total,
            'install_total_set' => $install_total_set,
            'install_total_no_set' => $install_total_no_set,
        ]);

        $this->assignconfig('column', array_keys($userlist));
        $this->assignconfig('userdata', array_values($userlist));

        return $this->view->fetch();
    }

    /**
     * 获取数据
     */
    public function getData()
    {
        $request = $this->request->request();
        $begin_time = isset($request['begin_time']) ? $request['begin_time'] : '';
        $end_time = isset($request['end_time']) ? $request['end_time'] : '';
        $uid_arr = '';
        if ($this->auth->id > 1 && $this->group_id >2) {
            $group_info = Db::name('ca_auth_group')->where(['status' => 'normal'])->select();
            $child_group = getAllChild($group_info, $this->group_id);
            array_push($child_group, $this->group_id);
            $uid_arr = Db::name('ca_auth_group_access')
                ->alias('ac')
                ->join('ca_admin a', 'a.id =ac.uid', 'right')
                ->where(['group_id' => ['in', $child_group], 'status' => 'normal'])
                ->column('uid');
            //  $user_id_arr = Db::name('ca_admin')->where(['id'=>['in',$uid_arr],'status'=>'normal'])->column('id');
           // $where_new['creater_id'] = ['in', $uid_arr];
            // var_dump($where_new['creater_id']);
        }
        $where_new = [
            'audit_status' => 1
        ];
        if ($begin_time) $where_new['createtime'] = ['between', [$begin_time, $end_time]];
        if ($uid_arr) $where_new['creater_id'] = ['in', $uid_arr];
        $distrition_num = Db::name('cd_admin')->where($where_new)->count();
        $where_put_new = [
            'audit_status' => 1
        ];
        if ($begin_time) $where_put_new['put_time'] = ['between', [$begin_time, $end_time]];
        if ($uid_arr) $where_put_new['admin_id'] = ['in', $uid_arr];
        $income = 0;
        $put_info = Db::name('card_put_info')->where($where_put_new)->field('put_num,put_price')->select();
        foreach ($put_info as $w => $v) {
            $income += $v['put_num'] * $v['put_price'] / 100;
        }
        // $income = $income;
        $where_card_new = [];
        if ($begin_time) $where_card_new['create_time'] = ['between', [$begin_time, $end_time]];
        if ($uid_arr) $where_card_new['admin_id'] = ['in', $uid_arr];
        $card_num = Db::name('card_log')->where($where_card_new)->count();
        $where_card_new = [
            'is_activate' => 1
        ];
        if ($begin_time) $where_card_new['create_time'] = ['between', [$begin_time, $end_time]];
        if ($uid_arr) $where_card_new['admin_id'] = ['in', $uid_arr];
        $card_activate_num = Db::name('card_log')->where($where_card_new)->count();
        //渠道占比数据
        $where_new = [
            'audit_status' => 1
        ];
        if ($uid_arr) $where_new['creater_id'] = ['in', $uid_arr];
        if ($begin_time) $where_new['createtime'] = ['between', [$begin_time, $end_time]];
        $distrition_y_info = Db::name('cd_admin')->where($where_new)
            ->group('distributor_type')
            ->field('distributor_type,count(*) as value')
            ->select();
        foreach ($distrition_y_info as $ww => &$vv) {
            $vv['name'] = $this->getDistributorType($vv['distributor_type']);
            //  $vv['value'] =   $vv['num'];
            unset($vv['distributor_type']);
        }
        $where_put_new = [
            'a.audit_status' => 1
        ];
        if ($uid_arr) $where_put_new['admin_id'] = ['in', $uid_arr];
        if ($begin_time) $where_put_new['put_time'] = ['between', [$begin_time, $end_time]];
        // $income = 0;
        $put_y_info = Db::name('card_put_info')
            ->alias('a')
            ->join('cd_admin ca', 'ca.id= a.distributor_id', 'left')
             ->group('distributor_type')
            ->where($where_put_new)
            ->field('distributor_type,sum(put_num * put_price) as value')->select();
        //  echo Db::name('card_put_info')->getLastSql();
        $new_info = [];
        foreach ($put_y_info as $wy => &$vy) {
            $vy['name'] = $this->getDistributorType($vy['distributor_type']);
            $vy['value'] = $vy['value'] / 100;
        }
        $where_card_new = [];
        if ($begin_time) $where_card_new['a.create_time'] = ['between', [$begin_time, $end_time]];
        if ($uid_arr) $where_card_new['admin_id'] = ['in', $uid_arr];
        $card_y_num = Db::name('card_log')
            ->alias('a')
            ->join('cd_admin ca', 'ca.id= a.distributor_id', 'left')
            ->where($where_card_new)
            ->group('distributor_type')
            ->field('distributor_type,count(*) as num')
            ->select();
        foreach ($card_y_num as $wcy => &$vcy) {
            $vcy['name'] = $this->getDistributorType($vcy['distributor_type']);
            $vcy['value'] = $vcy['num'];
        }
        $where_card_new = [
            'a.is_activate' => 1
        ];
        if ($uid_arr) $where_card_new['admin_id'] = ['in', $uid_arr];
        if ($begin_time) $where_card_new['a.create_time'] = ['between', [$begin_time, $end_time]];
        $card_y_activate_num = Db::name('card_log')
            ->alias('a')
            ->join('cd_admin ca', 'ca.id= a.distributor_id', 'left')
            ->where($where_card_new)
            ->group('distributor_type')
            ->field('distributor_type,count(*) as num')
            ->select();
        foreach ($card_y_activate_num as $wcay => &$vcay) {
            $vcay['name'] = $this->getDistributorType($vcay['distributor_type']);
            $vcay['value'] = $vcay['num'];
        }
        $result = [
            'distrition_num' => $distrition_num,
            'income' => $income,
            'card_num' => $card_num,
            'card_activate_num' => $card_activate_num,
            'active_info' => $card_y_activate_num,
            'card_info' => $card_y_num,
            'put_info' => $put_y_info,
            'distrition_info' => $distrition_y_info,
            'distrition_info_name' => array_column($distrition_y_info, 'name'),
            'put_info_name' => array_column($put_y_info, 'name'),
            'active_info_name' => array_column($card_y_activate_num, 'name'),
            'card_info_name' => array_column($card_y_num, 'name'),
        ];
        $this->success('获取成功', '', $result);
        return $this->view->fetch();
    }

    public function getDistributorType($distributor_type)
    {
        switch ($distributor_type) {
            case 1:
                $distributor_new_type = 'B端-大学';
                break;
            case 2:
                $distributor_new_type = 'B端-高中';
                break;
            case 3:
                $distributor_new_type = 'B端-中职';
                break;
            case 4:
                $distributor_new_type = 'B端-机构';
                break;
            case 5:
                $distributor_new_type = 'B端-个体';
                break;
            case 6:
                $distributor_new_type = 'B端-政府';
                break;
            case 7:
                $distributor_new_type = 'C端';
                break;
        }
        return $distributor_new_type;
    }


    /**
     * 渠道管理
     */
    public function get_table_data()
    {

        $request = $this->request->request();
        if ($this->request->isAjax()) {
            $where_new = [];
            $where_new = [
                'audit_status' => 1
            ];
            $distributor_type = isset($request['distributor_type']) ? $request['distributor_type'] : '';
            $begin_time = isset($request['begin_time']) ? $request['begin_time'] : '';
            $end_time = isset($request['end_time']) ? $request['end_time'] : '';
            if ($begin_time) $where_new['createtime'] = ['between', [$begin_time, $end_time]];
            if ($distributor_type) $where_new['distributor_type'] = $distributor_type;

            $list = Db::name('cd_admin')
                ->group('province_id')
                ->order('province_id desc')
                ->field('count(*) as num,province_id')
                ->where($where_new)
                ->select();
            $sql = Db::name('cd_admin')->getLastSql();
            foreach ($list as $w => &$v) {
                // $v['province'] = get_province_name($v['province_id']);
                $where_put_new = [
                    'a.audit_status' => 1,
                    'a.province_id' => $v['province_id'],
                ];
                if ($begin_time) $where_put_new['put_time'] = ['between', [$begin_time, $end_time]];
                // $income = 0;
                $card_put_info = Db::name('card_put_info')
                    ->alias('a')
                    ->where($where_put_new)
                    ->field('put_num,put_price')->select();
                $income = 0;
                foreach ($card_put_info as $wy => &$vy) {
                    $income += $vy['put_price'] * $vy['put_num'] / 100;
                }
                $v['income'] = $income;
                $where_card_new = [
                    'c.province_id' => $v['province_id'],
                ];
                if ($distributor_type) $where_card_new['distributor_type'] = $distributor_type;
                if ($begin_time) $where_card_new['c.create_time'] = ['between', [$begin_time, $end_time]];
                $v['card_num'] = Db::name('card_log')
                    ->alias('c')
                    ->join('cd_admin ca', 'ca.id= c.distributor_id', 'left')
                    ->where($where_card_new)->count();
                $v['card_sql'] = Db::name('card_log')->getLastSql();
                $where_card_new = [
                    'c.province_id' => $v['province_id'],
                    'is_activate' => 1
                ];
                if ($distributor_type) $where_card_new['distributor_type'] = $distributor_type;
                if ($begin_time) $where_card_new['c.create_time'] = ['between', [$begin_time, $end_time]];
                $v['card_activate_num'] = Db::name('card_log')
                    ->alias('c')
                    ->join('cd_admin ca', 'ca.id= c.distributor_id', 'left')
                    ->where($where_card_new)->count();
            }
            $sort = 'province_id';
            $array[0]['card_activate_num'] = array_sum(array_map(function ($val) {
                return $val['card_activate_num'];
            }, $list));
            $array[0]['card_num'] = array_sum(array_map(function ($val) {
                return $val['card_num'];
            }, $list));
            $array[0]['income'] = array_sum(array_map(function ($val) {
                return $val['income'];
            }, $list));
            $array[0]['num'] = array_sum(array_map(function ($val) {
                return $val['num'];
            }, $list));
            $array[0]['province_id'] = 99;
            $list = array_merge($array, $list);
            $coins = array_column($list, $sort);
            array_multisort($coins, SORT_DESC, $list);
            $result = array("total" => count($list), "rows" => $list, "sql" => $sql);

            return json($result);
        }
        $this->assign('province', get_pro());
        $this->assign('city', []);
        // $this->assign('dis_num', $dis_num);
        return $this->view->fetch();
    }
}
